package com.atguigu.day04;

import com.atguigu.utils.IntegerSource;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class Example3 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntegerSource())
                .keyBy(r -> 1)
                .process(new MinMaxValue())
                .print();

        env.execute();
    }

    public static class MinMaxValue extends KeyedProcessFunction<Integer, Integer, String> {
        private ValueState<Tuple2<Integer, Integer>> accumulator;
        // 保存定时器时间戳的状态变量
        private ValueState<Long> timerTs;
        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            accumulator = getRuntimeContext().getState(
                    new ValueStateDescriptor<Tuple2<Integer, Integer>>(
                            "acc",
                            Types.TUPLE(Types.INT, Types.INT)
                    )
            );

            timerTs = getRuntimeContext().getState(
                    new ValueStateDescriptor<Long>(
                            "timer",
                            Types.LONG
                    )
            );
        }

        @Override
        public void processElement(Integer value, Context ctx, Collector<String> out) throws Exception {
            if (accumulator.value() == null) {
                accumulator.update(Tuple2.of(value, value));
            } else {
                accumulator.update(
                        Tuple2.of(
                                value > accumulator.value().f0 ? value : accumulator.value().f0,
                                value < accumulator.value().f1 ? value : accumulator.value().f1
                        )
                );
            }

            if (timerTs.value() == null) {
                // 如果timerTs.value()为空，说明没有注册过定时器
                long currTs = ctx.timerService().currentProcessingTime();
                long tenSecLater = currTs + 10 * 1000L;
                // 注册一个10秒中之后的定时器
                ctx.timerService().registerProcessingTimeTimer(tenSecLater);
                // 还要将定时器的时间戳保存在timerTs中
                timerTs.update(tenSecLater);
            }
        }

        // 使用定时器来向下游发送数据
        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            super.onTimer(timestamp, ctx, out);
            out.collect("流上的最大值：" + accumulator.value().f0 + ";" +
                    "流上的最小值：" + accumulator.value().f1);
            // 将timerTs.value()清空为null
            timerTs.clear();
        }
    }
}
